//
//  MSLocationManager.m
//  MSJD
//
//  Created by xiangbo on 2018/10/21.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSLocationManager.h"

static NSString *const kMSLocationCityKey = @"kMSLocationCityKey";

@interface MSLocationManager ()<CLLocationManagerDelegate>

//地理编码对象
@property (nonatomic, strong)CLGeocoder *geocoder;
@property (nonatomic,strong)CLPlacemark *currentPlace;
@property (nonatomic,strong)NSString *currentCity;

@end

@implementation MSLocationManager

+(instancetype)shareInstance{
    static MSLocationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MSLocationManager alloc] init];
//        [manager locationStart];
    });
    return manager;
}

//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        if ([[[UIDevice currentDevice] systemVersion]floatValue] >= 8.0) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        [self showErrorTipWithErrorMsg:@"定位服务当前可能尚未打开，请设置打开！"];
    }
}

- (NSString *)currentLocalCityString {
    NSString *cityStr = [[NSUserDefaults standardUserDefaults] objectForKey:kMSLocationCityKey];
    return cityStr;
}

#pragma mark - CoreLocation Delegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    _WEAKSELF
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count >0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            NSString *currCity = placemark.locality;
            if (!currCity) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                currCity = placemark.administrativeArea;
            }
            NSString *newCityStr = [NSString stringWithFormat:@"%@,%@",placemark.administrativeArea,currCity];
            if (![weakSelf.currentCity isEqualToString:newCityStr]) {
                // 当城市内容变化时，修改属性值
                weakSelf.currentCity = newCityStr;
                // 修改本地存储的城市字符串
                [[NSUserDefaults standardUserDefaults] setObject:newCityStr forKey:kMSLocationCityKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 更新Home界面的本地字符串的内容
                [[NSNotificationCenter defaultCenter] postNotificationName:@"locationCityChangedNty" object:nil];
            }
            weakSelf.currentPlace = placemark;
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        
    }    
}

- (void)showErrorTipWithErrorMsg:(NSString *)errorMsg {
    [MBProgressHUD showDefaultHUDWithText:errorMsg toView:[UIApplication sharedApplication].keyWindow];
}

#pragma mark -Property

- (CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.distanceFilter = 1;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        _locationManager.delegate = self;
    }
    return _locationManager;
}

//懒加载---给地理编码对象开空间
- (CLGeocoder *)geocoder {
    if (_geocoder == nil) {
        self.geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

@end
